Fork me on GitHub

2018.4.23 leetcode 即便是慵懒的星期一,也不能落下

今天做的三题easy竟然没百度…也没看disscuss

2018.4.23

Array - 747. Largest Number At Least Twice of Others

题目详情

In a given integer array nums, there is always exactly one largest element.

Find whether the largest element in the array is at least twice as much as every other number in the array.

If it is, return the index of the largest element, otherwise return -1.

在给定的整数数组中nums,只有一个最大的元素。

查找数组中有没元素是这个最大值的两倍或者以上

如果有,则返回最大元素的索引,否则返回-1。

Example:

Input: nums = [3, 6, 1, 0]

Output: 1

思路

  • 很简单,找到前两最大值,再进行比较即可

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
var dominantIndex = function(nums) {
let max1 = max2 = maxIndex = 0
for(let i = 0; i < nums.length; i++) {
if(nums[i] > max2) {
max2 = Math.min(nums[i],max1)
if(nums[i] > max1) {
max1 = nums[i]
maxIndex = i
}
}
}
return max1 / max2 >= 2 ? maxIndex : -1
};

Array - 283. Move Zeroes

题目详情

Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).

找出数组中最长连续增加子序列的长度

Example1:

Input: [1,3,5,4,7]

Output: 3

Explanation: 最长连续增加子序列为[1,3,5],其长度为3.

Example2:

Input: [2,2,2,2,2]

Output: 1

Explanation: 最长连续增长子序列为[2],其长度为1。

思路

  • 遍历的时候判断当前元素是否大于前一个元素,

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @param {number[]} nums
* @return {number}
*/
var findLengthOfLCIS = function(nums) {
if(nums.length === 0) return 0
let maxContLen = currContLen = 1
for(let i = 1, len = nums.length; i < len; i++) {
if(nums[i] <= nums[i-1]) {
currContLen = 1
} else if(nums[i] - nums[i-1] > 0) {
currContLen++
maxContLen = Math.max(currContLen, maxContLen)
}
}
return maxContLen
};

Array - 724. Find Pivot Index

题目详情

Given an array of integers nums, write a method that returns the “pivot” index of this array.

We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.

If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.

给定一个数组,一找到元素左边求和等于元素右边求和的元素就返回他的索引,没有就返回-1

Example:

Input: nums = [1, 7, 3, 6, 5, 6]

Output: 3

思路

  • 先把整个数组求和
  • 再遍历一遍,一遍遍历一遍进行左边的求和,每次求和都判断总和减当前元素值和当前的左数组和 是否等于 左数组和

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @param {number[]} nums
* @return {number}
*/
var pivotIndex = function(nums) {
let total = 0
for(let i = 0, len = nums.length; i < len; i++) {
total += nums[i]
}
let leftS = 0
for(let i = 0, len = nums.length; i < len; i++) {
if(total - leftS - nums[i] === leftS) {
return i
}
leftS += nums[i]
}
return -1
};
-------------本文结束感谢您的阅读-------------
分享